package com.mark.springsecurity.domain;

import com.mark.springsecurity.dto.req.SysRoleCmd;
import com.mark.springsecurity.dto.req.vo.SysAuthorityVo;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.hibernate.annotations.Type;
import org.springframework.data.annotation.CreatedBy;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedBy;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Builder
@EntityListeners(AuditingEntityListener.class)
public class SysRole {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;

    @Column(nullable = false)
    @Type(type = "yes_no")
    private Boolean enabled;

    @CreatedBy
    @Column(nullable = false, length = 50, updatable = false)
    private String createdBy;

    @CreatedDate
    @Column(nullable = false, updatable = false)
    private LocalDateTime createdDate;

    @LastModifiedBy
    @Column(length = 50)
    private String lastModifiedBy;

    @LastModifiedDate
    private LocalDateTime lastModifiedDate;

    @ManyToMany(targetEntity = SysAuthority.class)
    private Set<SysAuthority> authorities; // 角色和权限是多对多的关系

    public void update(SysRoleCmd sysRoleCmd) {
        this.name = sysRoleCmd.getName();
        this.authorities = sysRoleCmd.getAuthorities().stream().map(SysAuthorityVo::buildAuthority).collect(Collectors.toSet());
    }

    public void remove() {
        this.enabled = Boolean.FALSE;
    }
}
